from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import os
import time
import shutil
from werkzeug.utils import secure_filename
from API.text2img import text_to_img
from pc_send import pc_send 
from API.TextTransfer import text_2_image

# 初始化 Flask
app = Flask(__name__)
CORS(app)  # 允许跨域（开发用，生产环境需限制来源）

# 配置文件上传
UPLOAD_FOLDER = 'uploads'  # 上传文件存储目录
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'mp3', 'wav'}  # 允许的文件类型
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 确保上传目录存在
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
def save_to_file(location):
    with open(os.path.join(UPLOAD_FOLDER, 'destination.txt'), 'w',encoding='utf-8') as file:
        file.write(location)
def transfer_img(filename):
    target_name = 'uploads/' + filename.split('.')[0] + '_t.jpg'
    output_name = 'generate_image.jpg'
    shutil.copy(target_name, output_name)
    print(f"{target_name} 已复制为 {output_name}")
    pass  
# 检查文件扩展名是否合法
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 模拟数据库（存储文本-图片映射）
FAKE_IMAGE_DB = {
    "巴黎": ["images/paris1.jpg", "images/paris2.jpg"],
    "东京": ["images/tokyo1.jpg"],
    "默认": ["images/not_found.jpg"]
}

# 1. 处理文本输入（如搜索地点）
@app.route('/process_location', methods=['POST'])
def handle_search():
    if not request.is_json:
        return jsonify({"error": "请求必须是JSON"}), 400
    
    data = request.get_json()
    location = data.get('location')
    
    if not location:
        return jsonify({"error": "缺少 location 参数"}), 400
    print(f"后端成功获取到前端输入的文本: 【{location}】")
    save_to_file(location)
    text_to_img(location)
    pc_send()
    # 模拟处理延迟
    time.sleep(0.5)
    
    # 返回匹配的图片
    image_urls = FAKE_IMAGE_DB.get(location, FAKE_IMAGE_DB["默认"])
    return jsonify({
        "message": "搜索成功",
        "location": location,
        "images": image_urls
    })

@app.route('/api/upload-text', methods=['POST'])
def upload_mind():
    print('hello')
    # 3. 从 request.form 中获取名为 'text' 的字段
    #    对应前端的: formData.append("text", textContent);
    text_content = request.form.get('text')

    # 4. 后端再次验证，确保数据不为空
    if not text_content or text_content.strip() == "":
        # 5. 返回一个失败的JSON，包含 success: false 和 message
        #    对应前端的: else { alert("提交失败：" + data.message); }
        return jsonify({"success": False, "message": "感悟内容不能为空"}), 400

    # --- 这里是你的核心业务逻辑 ---
    # 比如保存到数据库、写入文件、或者调用其他服务等
    print(f"成功接收到前端发来的感悟: '{text_content}'")
    # -----------------------------
    text_2_image(text_content)
    pc_send()
    # 6. 返回一个成功的JSON，包含 success: true
    #    对应前端的: if (data.success) { ... }
    return jsonify({"success": True, "message": "感悟提交成功！"}), 200

# 2. 处理图片上传
@app.route('/api/upload/image', methods=['POST'])
def upload_image():
    if 'file' not in request.files:
        return jsonify({"error": "未上传文件"}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "文件名为空"}), 400
    
    if not allowed_file(file.filename):
        return jsonify({"error": "文件类型不支持"}), 400
    print("接收到图片")
    # 安全存储文件名（防止路径遍历攻击）
    filename = secure_filename(file.filename)
    print(filename)
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    transfer_img(filename)
    time.sleep(2.5)
    pc_send()
    
    return jsonify({
        "message": "图片上传成功",
        "filename": filename,
        "url": f"/uploads/{filename}"  # 前端可通过此URL访问文件
    })

# 3. 处理音频上传
@app.route('/api/upload-audio', methods=['POST'])
def upload_audio():
    if 'audio' not in request.files:
        return jsonify({"error": "未上传文件"}), 400
    
    file = request.files['audio']
    if file.filename == '':
        return jsonify({"error": "文件名为空"}), 400
    
    if not allowed_file(file.filename):
        return jsonify({"error": "仅支持 MP3/WAV 格式"}), 400
    
    filename = secure_filename(file.filename)
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    text_2_image("驼铃悠悠")
    pc_send()
    return jsonify({
        "message": "音频上传成功",
        "filename": filename,
        "url": f"/uploads/{filename}"
    })

# 4. 提供上传的文件访问（如 /uploads/filename.jpg）
@app.route('/uploads/<filename>')
def serve_uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

# 5. 统一错误处理
@app.errorhandler(404)
def not_found(error):
    return jsonify({"error": "API不存在"}), 404

@app.errorhandler(500)
def server_error(error):
    return jsonify({"error": "服务器内部错误"}), 500

# 启动服务器
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)